angular.module('global', [])

.service('CheckUpdateService',function($q,$http,$rootScope,$ionicPopup,$ionicLoading, $cordovaAppVersion, $cordovaFileTransfer, $cordovaFile, $cordovaFileOpener2,$timeout){
  var fileTransferDir,fileDir;
  var getServerJson = function(){
    var defer=$q.defer();
    $http.jsonp('http://binggolink.com/app/version.php?callback=JSON_CALLBACK')
    .success(function(data){
      defer.resolve(data);//发送执行成功的消息
    }).error(function(status, headers, config){
      defer.reject();//执行失败
    });
    return defer.promise;//返回获取的数据
  };

  var prepearDir = function(){
    if (ionic.Platform.isAndroid()) {
      console.log('cordova.file.externalDataDirectory: ' + cordova.file.externalDataDirectory);
      myFsRootDirectory1 = 'file:///storage/emulated/0/';
      myFsRootDirectory2 = 'file:///storage/sdcard0/';
      fileTransferDir = cordova.file.externalDataDirectory;
      if (fileTransferDir.indexOf(myFsRootDirectory1) === 0) {
        fileDir = fileTransferDir.replace(myFsRootDirectory1, '');
      }
      if (fileTransferDir.indexOf(myFsRootDirectory2) === 0) {
        fileDir = fileTransferDir.replace(myFsRootDirectory2, '');
      }
      console.log('Android FILETRANSFERDIR: ' + fileTransferDir);
      console.log('Android FILEDIR: ' + fileDir);
    }
    if (ionic.Platform.isIOS()) {
      console.log('cordova.file.documentsDirectory: ' + cordova.file.documentsDirectory);
      fileTransferDir = cordova.file.documentsDirectory;
      fileDir = '';
      console.log('IOS FILETRANSFERDIR: ' + fileTransferDir);
      console.log('IOS FILEDIR: ' + fileDir);
    }
    if (ionic.Platform.isAndroid() || ionic.Platform.isIOS()) {
    }
  };

  // 显示是否更新对话框
  var showUpdateConfirm = function(versionData) {
		var updateConfirm = $ionicPopup.confirm({
      title: '新版本准备好了！',
      template: ''+(versionData.changeLog || ''),
      cancelText: '取消',
      okText: '升级',
      okType: 'button-royal'
    });

    updateConfirm.then(function (res) {
      if(res) {
        var url = encodeURI("http://binggolink.com/app/"+versionData.file);
        console.log(cordova.file);
        var folderName ="elink";
        prepearDir();
        var targetPath = fileTransferDir+versionData.file;
        var trustHosts = true;
        var options = {};
        $cordovaFileTransfer.download(url, targetPath, options, trustHosts).then(function (result) {
          $timeout(function(){
            $cordovaFileOpener2.open(targetPath, 'application/vnd.android.package-archive')
            .then(function () {
            }, function (err) {
            });
          },500);

        }, function (err) {
          console.log(err);
          alert('下载失败');
        }, function (progress) {
          $timeout(function () {
            var downloadProgress = (progress.loaded / progress.total) * 100;
            $ionicLoading.show({
              template: '<div class="process-bar">'+
                '<div class="done" style="width:'+Math.floor(downloadProgress) + '%">'+
                   '<div class="current"></div>'+
                '</div></div>'+
                '<div ng-if="'+(Math.floor(downloadProgress)<100)+'">' + Math.floor(downloadProgress) + '%</div>'+
                '<div ng-if="'+(Math.floor(downloadProgress)===100)+'">下载完成，请完成安装</div>'
            });
          });
        });
      } else {
        if(versionData.updateType=='force'){
        	ionic.Platform.exitApp();
        }
      }
    });
  };

  this.checkUpdate = function(){
    getServerJson().then(function(versionData){
       console.log(versionData);
      $cordovaAppVersion.getVersionNumber().then(function (version) {
        if (version != versionData.version) {
        	$rootScope.forceUpdate = true;
	        setTimeout(function () {
	            //showUpdateConfirm(versionData);
	        }, 800);
        }
      });
    });
  };
})

.service('StatusBarService', function($cordovaStatusbar) {

  this.setStyle = function(){
    if (window.cordova){
      if(window.cordova.platformId == 'android') {
        StatusBar.backgroundColorByHexString("#FF7800");
        StatusBar.styleLightContent();
      }else if(window.cordova.platformId == 'ios'){
        $cordovaStatusbar.overlaysWebView(false);
        $cordovaStatusbar.style(1);
        StatusBar.styleLightContent();
        $cordovaStatusbar.styleHex('#F70');
      }
    }
  };
})

.service('BackButtonService', function($ionicPlatform,$ionicHistory,$rootScope,$cordovaToast) {
  this.registerBackButtonAction = function(){
    $ionicPlatform.registerBackButtonAction(function (e) {
      if ( !$ionicHistory.backView() || $ionicHistory.currentStateName() == 'elink.gateway') {
        if ($rootScope.backButtonPressedOnceToExit) {
          ionic.Platform.exitApp();
        } else {
          $rootScope.backButtonPressedOnceToExit = true;
          $cordovaToast.showShortBottom('再按一次退出易联锁');
          setTimeout(function () {
              $rootScope.backButtonPressedOnceToExit = false;
          }, 2000);
        }
      }
      else if ($ionicHistory.backView()) {
          console.log("-----------------------3");
          $ionicHistory.goBack();

      } else {
        $rootScope.backButtonPressedOnceToExit = true;
        $cordovaToast.showShortBottom('再按一次退出系统');
        setTimeout(function () {
            $rootScope.backButtonPressedOnceToExit = false;
        }, 2000);
        console.log("-----------------------4");
      }
      e.preventDefault();
      return false;
    }, 101 );
  };

});
